package qeug.shsh.facde.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.drew.lang.annotations.NotNull;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.openapi.common.custom.annotation.ApiParam;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.custom.annotation.ApiResponseBody;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import qeug.shsh.facde.info.SupplierInfo;
import qeug.shsh.facde.resultext.SupplierResulText;
import qeug.shsh.helper.FacadeHelper;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * &#064;description：供应商接口
 */
@ApiController(value = "QuerySupplierController", desc = "金蝶供应商接口，自定义插件")
public class SupplierController implements Serializable {

//    private final static Log logger = LogFactory.getLog(SupplierController.class);//日志

    @ApiPostMapping(value = "/shsh_supplier", desc = "供应商api接口")
    public CustomApiResult<@ApiResponseBody("返回参数") SupplierResulText> SHSupplierQuery
            (@NotNull @ApiParam(value = "入参") SupplierInfo model) {
        /*
          返回值对象
         */
        SupplierResulText supplierResulText = new SupplierResulText();
        int failCount = 0;//失败数量
        int successCount = 0;//成功数量
        /*
          返回信息
         */
        ArrayList<SupplierResulText.ResultBean> results = new ArrayList<>();
        /*
          接口日志
         */
        StringBuilder msgBuilder = new StringBuilder();

        // 供应商入参集合
        List<SupplierInfo.DataBean> data = model.getData();
        for (int i = 0; i < data.size(); i++) {
//            StringBuffer stringBuffer = new StringBuffer();//错误信息提示
            SupplierInfo.DataBean dataBean = data.get(i);
            String id = dataBean.getMDM_NO();//分发id
            String number = dataBean.getLIFNR();//编码
            String status = dataBean.getSTATUS();//使用状态
            if (StringUtils.isBlank(number)) {
                msgBuilder.append("第").append(i + 1).append("条数据，编码为空不能保存!");
                SupplierResulText.ResultBean failure = SupplierResulText.failure(i, "供应商编码不能为空", id);
                results.add(failure);//将返回结果数据存放到集合中
                supplierResulText.setResult(results);//将集合重新传给返回值参数
                failCount++;//错误信息+1
            } else {
                // 检查编码是否存在
                DynamicObject existingSupplier = BusinessDataServiceHelper.loadSingle("bd_supplier", new QFilter("number", "=", number).toArray());
                String message = null;
                if (existingSupplier != null && "1".equals(status)) {
                    // 编码已存在，执行修改操作
                    DynamicObject supplier = existingSupplier;
                    supplier.set("enable", dataBean.getSTATUS());//使用状态
                    supplier.set("status", "C");//数据状态默认已审核
                    String fullName = dataBean.getFULL_NAME();
                    if (StringUtils.isBlank(fullName)) {
                        DynamicObject full = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter("number", "=", number).toArray());
                        fullName = full.getString("name");
                    }
                    supplier.set("name", fullName);//单位全称
                    supplier.set("simplename", dataBean.getNAME1());//单位简称
                    supplier.set("internal_company", FacadeHelper.getDynamicObject("bos_org", "name", dataBean.getVBUND()));//贸易伙伴（内部单位）
                    supplier.set("bizpartner_address", dataBean.getADDRESS());//地址
                    supplier.set("bizpartner_phone", dataBean.getTEL_NUMBER());//电话号
                    supplier.set("bizpartner_fax", dataBean.getFAX_NUMBER());//传真号
                    supplier.set("societycreditcode", dataBean.getSORT1());//统一信用代码
                    // 国家信息处理
                    String code = dataBean.getLAND1();
                    String name = dataBean.getLAND2();
                    String targetField = "qeug_assistantfield1";
                    QFilter[] filters;
                    if (StringUtils.isNotBlank(code)) {
                        filters = new QFilter[]{new QFilter("number", "=", code)};
                    } else {
                        filters = new QFilter[]{new QFilter("name", "=", name)};
                    }
                    DynamicObject country = BusinessDataServiceHelper.loadSingle("bos_assistantdata_detail", filters);
                    supplier.set(targetField, country);

                    // 地区信息处理（复用变量）
                    code = dataBean.getREGIO();
                    name = dataBean.getREGIO1();
                    targetField = "qeug_assistantfield";
                    if (StringUtils.isNotBlank(code)) {
                        filters = new QFilter[]{new QFilter("number", "=", code)};
                    } else {
                        filters = new QFilter[]{new QFilter("name", "=", name)};
                    }
                    DynamicObject region = BusinessDataServiceHelper.loadSingle("bos_assistantdata_detail", filters);
                    supplier.set(targetField, region);

                    // 城市信息处理（复用变量）
                    code = dataBean.getORT02();
                    name = dataBean.getORT01();
                    targetField = "qeug_admindivision";
                    if (StringUtils.isNotBlank(code)) {
                        filters = new QFilter[]{new QFilter("number", "=", code)};
                    } else {
                        filters = new QFilter[]{new QFilter("name", "=", name)};
                    }
                    DynamicObject city = BusinessDataServiceHelper.loadSingle("bos_assistantdata_detail", filters);
                    supplier.set(targetField, city);

                    supplier.set("qeug_isylgys", dataBean.getRAWMATERIAL());//是否原料供应商
                    supplier.set("regcapital", dataBean.getREGISTER());//注册资金
                    supplier.set("postal_code", dataBean.getEMAIL());//电子邮箱

                    //输入只有地区名称、编码，输出为只有地区名称
                    //输入有城市名称、编码和地区名称、编码，输出为城市名称和地区名称；
/*                    if (StringUtils.isNotBlank(ort01) || StringUtils.isNotBlank(ort02)) {
                        if (StringUtils.isNotBlank(ort01)) {
                            QFilter f1 = new QFilter("name", QCP.equals, ort01);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                supplier.set("admindivision", collection.get("id"));
                            }
                        } else {
                            QFilter f1 = new QFilter("number", QCP.equals, ort02);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                supplier.set("admindivision", collection.get("id"));
                            }
                        }
                    } else {
                        if (StringUtils.isNotBlank(regio1)) {
                            //不为空且不为null
                            QFilter f1 = new QFilter("name", QCP.equals, regio1);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                supplier.set("admindivision", collection.get("id"));
                            }
                        } else {
                            QFilter f1 = new QFilter("number", QCP.equals, regio);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                supplier.set("admindivision", collection.get("id"));
                            }
                        }
                    }*/

                    List<SupplierInfo.DataBean.EntrySort> sorts = dataBean.getSorts();//分类标准
                    if (sorts != null) {
                        DynamicObjectCollection groupstandardCollection = supplier.getDynamicObjectCollection("entry_groupstandard");//分类标准
                        groupstandardCollection.clear();
                        DynamicObjectType groupstandardType = groupstandardCollection.getDynamicObjectType();
                        SupplierInfo.DataBean.EntrySort entrySort = sorts.get(0);
                        DynamicObject SortEntry = new DynamicObject(groupstandardType);
                        String ktokk = entrySort.getKTOKK();//供应商账户组代码
                        DynamicObject supplierGroupNumber = BusinessDataServiceHelper.loadSingle("bd_suppliergroup", new QFilter("number", "=", ktokk).toArray());
                        DynamicObject suppliergroupstandard = BusinessDataServiceHelper.loadSingle("bd_suppliergroupstandard", new QFilter("number", "=", "JBFLBZ").toArray());
                        SortEntry.set("groupid", supplierGroupNumber);//供应商账户组代码
                        SortEntry.set("standardid",suppliergroupstandard);//供应商分类标准
                        if (ktokk == null) {
                            String ktokk1 = entrySort.getKTOKK1();//供应商账户组名称
                            DynamicObject supplierGroupName = BusinessDataServiceHelper.loadSingle("bd_suppliergroup", new QFilter("name", "=", ktokk1).toArray());
                            SortEntry.set("groupid", supplierGroupName);//供应商账户组名称
                            SortEntry.set("standardid",supplierGroupNumber);//供应商分类标准
                        }
                        groupstandardCollection.add(SortEntry);
                    }

                    List<SupplierInfo.DataBean.EntryBanks> banks = dataBean.getBanks();//银行分录
                    DynamicObjectCollection banksCollection = supplier.getDynamicObjectCollection("entry_bank");//银行分录
                    // 移除现有的银行分录
                    banksCollection.clear();
                    DynamicObjectType bankType = banksCollection.getDynamicObjectType();
                    for (int k = 0; k < banks.size(); k++) {
                        SupplierInfo.DataBean.EntryBanks entryBanks = banks.get(k);
                        DynamicObject banksEntry = new DynamicObject(bankType);
                        //同一个银行账号 不能同时存在在不同编码的客商内
                        String bankn = entryBanks.getBANKN();
                        if (bankn != null) {
                            // 检查银行账号是否已存在于其他编码中
                            //为true银行账号已存在于其他编码中，为false 银行账号不存在于其他编码中
                            boolean isBankAccountExists = checkBankAccountExists(bankn);
                            if (!isBankAccountExists) {
                                //现在为false
                                banksEntry.set("bankaccount", bankn);//银行账号
                            } else {
                                //现在为true
                                DynamicObject bill1 = BusinessDataServiceHelper.loadSingle("bd_supplier", new QFilter("entry_bank.bankaccount", "=", bankn).toArray());
                                String number2 = bill1.getString("number");
                                if (number2.equals(number)) {
                                    banksEntry.set("bankaccount", bankn);//银行账号
                                } else {
                                    msgBuilder.append("第").append(i + 1).append("条数据，银行账号重复，不能保存!");
                                    SupplierResulText.ResultBean failure = SupplierResulText.failure(i, "银行账号已存在于其他编码中", id);
                                    results.add(failure);//将返回结果数据存放到集合中
                                    supplierResulText.setResult(results);//将集合重新传给返回值参数
                                    failCount++;//错误信息+1
                                }
                            }
                        }

                        String koinh = entryBanks.getKOINH();
                        banksEntry.set("accountname", koinh);//开户账户名(账户名称)
                        String currencyNum = entryBanks.getCURRENCYCODE();//币种代码
                        DynamicObject currencyNumber = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("number", "=", currencyNum).toArray());
                        banksEntry.set("currency", currencyNumber);//币种代码
                        if (currencyNum == null) {
                            String currencyname = entryBanks.getCURRENCYNAME();//币种名称
                            DynamicObject currencyName = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("name", "=", currencyname).toArray());
                            banksEntry.set("currency", currencyName);//币种名称
                        }
                        String bankl = entryBanks.getBANKL(); //开户银行通过联行号获取
                        DynamicObject bank = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("union_number", "=", bankl).toArray());
                        banksEntry.set("bank", bank);//开户银行
                        if (bankl == null) {
                            String bankName1 = entryBanks.getBANKN();//开户银行名称
                            DynamicObject bankName2 = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("name", "=", bankName1).toArray());
                            banksEntry.set("bank", bankName2);//开户银行名称
                        }
                        String iban = entryBanks.getBANKS();
                        banksEntry.set("iban", iban);//银行国家代码（国际银行账户号码）
                        //第一行银行信息为默认
                        if (k == 0) {
                            banksEntry.set("isdefault_bank", true);//默认
                        } else {
                            banksEntry.set("isdefault_bank", false);
                        }
                        banksCollection.add(banksEntry);
                    }
//                    OperationResult updateResult = SaveServiceHelper.saveOperate("bd_supplier", new DynamicObject[]{supplier});
                    OperationResult operationResult = OperationServiceHelper.executeOperate("save", "bd_supplier", new DynamicObject[]{supplier});
                    for (IOperateInfo errInfo : operationResult.getAllErrorOrValidateInfo()) {
                        message = errInfo.getMessage();
                    }
                    System.out.println();
                } else if (!"1".equals(status)) {
                    //使用状态不为1，不接受新增和修改
                    msgBuilder.append("第").append(i + 1).append("条数据，使用状态为停用，不接受新增和修改!");
                    SupplierResulText.ResultBean failure = SupplierResulText.failure(i, "使用状态为停用，不接受新增和修改", id);
                    results.add(failure);//将返回结果数据存放到集合中
                    supplierResulText.setResult(results);//将集合重新传给返回值参数
                    failCount++;
                    supplierResulText.setFailCount(failCount);//失败数量
                } else {
                    String fullName = dataBean.getFULL_NAME();//单位全称
                    if (StringUtils.isBlank(fullName)) {
                        //如果fullName为空或者为空字符串，则执行接下来的代码块
                        msgBuilder.append("第").append(i + 1).append("条数据，名称为空不能保存!");
                        SupplierResulText.ResultBean failure = SupplierResulText.failure(i, "供应商名称不能为空", id);
                        results.add(failure);//将返回结果数据存放到集合中
                        supplierResulText.setResult(results);//将集合重新传给返回值参数
                        failCount++;//错误信息+1
                    }
                    String forShort = dataBean.getNAME1();//单位简称
                    String createOrg = dataBean.getCREATEORG("盛虹集团");//创建组织“默认盛虹集团”
                    DynamicObject createOrgName = BusinessDataServiceHelper.loadSingle("bos_adminorg", new QFilter("name", "=", createOrg).toArray());
                    String vbund = dataBean.getVBUND();//贸易伙伴（内部单位）
                    DynamicObject vbundName = FacadeHelper.getDynamicObject("bos_org", "name", vbund);
                    String address = dataBean.getADDRESS();//地址
                    String tel_number = dataBean.getTEL_NUMBER();//电话号
                    String fax_number = dataBean.getFAX_NUMBER();//传真号
                    String sort1 = dataBean.getSORT1();//统一信用代码

                    String rawmaterial = dataBean.getRAWMATERIAL(); //是否原料供应商
                    String register = dataBean.getREGISTER(); //注册资金
                    String email = dataBean.getEMAIL();//电子邮箱
//            String pstlz = dataBean.getPSTLZ();//邮编
//            String extension = dataBean.getEXTENSION(); //电话分机号
//            String fax2 = dataBean.getFAX2(); //注传真分机号

                    ORM orm = ORM.create();
                    DynamicObject supplier = orm.newDynamicObject("bd_supplier");
                    supplier.set("number", number);//编码
                    supplier.set("name", fullName);//单位全称
                    supplier.set("simplename", forShort);//单位简称
                    supplier.set("enable", status);//使用状态
                    supplier.set("status", "C");//数据状态默认已审核
                    supplier.set("createorg", createOrgName);//创建组织
                    supplier.set("ctrlstrategy", "2");//控制策略“默认自由分配”
                    supplier.set("internal_company", vbundName);//贸易伙伴（内部单位）
                    supplier.set("bizpartner_address", address);//地址
                    supplier.set("bizpartner_phone", tel_number);//电话号
                    supplier.set("bizpartner_fax", fax_number);//传真号
                    supplier.set("societycreditcode", sort1);//统一信用代码
                    // 国家信息处理
                    String code = dataBean.getLAND1();
                    String name = dataBean.getLAND2();
                    String targetField = "qeug_assistantfield1";
                    QFilter[] filters;
                    if (StringUtils.isNotBlank(code)) {
                        filters = new QFilter[]{new QFilter("number", "=", code)};
                    } else {
                        filters = new QFilter[]{new QFilter("name", "=", name)};
                    }
                    DynamicObject country = BusinessDataServiceHelper.loadSingle("bos_assistantdata_detail", filters);
                    supplier.set(targetField, country);

                    // 地区信息处理（复用变量）
                    code = dataBean.getREGIO();
                    name = dataBean.getREGIO1();
                    targetField = "qeug_assistantfield";
                    if (StringUtils.isNotBlank(code)) {
                        filters = new QFilter[]{new QFilter("number", "=", code)};
                    } else {
                        filters = new QFilter[]{new QFilter("name", "=", name)};
                    }
                    DynamicObject region = BusinessDataServiceHelper.loadSingle("bos_assistantdata_detail", filters);
                    supplier.set(targetField, region);

                    // 城市信息处理（复用变量）
                    code = dataBean.getORT02();
                    name = dataBean.getORT01();
                    targetField = "qeug_admindivision";
                    if (StringUtils.isNotBlank(code)) {
                        filters = new QFilter[]{new QFilter("number", "=", code)};
                    } else {
                        filters = new QFilter[]{new QFilter("name", "=", name)};
                    }
                    DynamicObject city = BusinessDataServiceHelper.loadSingle("bos_assistantdata_detail", filters);
                    supplier.set(targetField, city);

                    supplier.set("qeug_isylgys", rawmaterial);//是否原料供应商
                    supplier.set("regcapital", register);//注册资金
                    supplier.set("postal_code", email);//电子邮箱

                    List<SupplierInfo.DataBean.EntrySort> sorts = dataBean.getSorts();//分类标准
                    if (sorts != null) {
                        DynamicObjectCollection groupstandardCollection = supplier.getDynamicObjectCollection("entry_groupstandard");//分类标准
                        DynamicObjectType groupstandardType = groupstandardCollection.getDynamicObjectType();
                        SupplierInfo.DataBean.EntrySort entrySort = sorts.get(0);
                        DynamicObject SortEntry = new DynamicObject(groupstandardType);
                        String ktokk = entrySort.getKTOKK();//供应商账户组代码
                        DynamicObject supplierGroupNumber = BusinessDataServiceHelper.loadSingle("bd_suppliergroup", new QFilter("number", "=", ktokk).toArray());
                        DynamicObject suppliergroupstandard = BusinessDataServiceHelper.loadSingle("bd_suppliergroupstandard", new QFilter("number", "=", "JBFLBZ").toArray());
                        SortEntry.set("groupid", supplierGroupNumber);//供应商账户组代码
                        SortEntry.set("standardid",suppliergroupstandard);//供应商分类标准
                        if (ktokk == null) {
                            String ktokk1 = entrySort.getKTOKK1();//供应商账户组名称
                            DynamicObject supplierGroupName = BusinessDataServiceHelper.loadSingle("bd_suppliergroup", new QFilter("name", "=", ktokk1).toArray());
                            SortEntry.set("groupid", supplierGroupName);//供应商账户组名称
                            SortEntry.set("standardid",suppliergroupstandard);//供应商分类标准
                        }
                        groupstandardCollection.add(SortEntry);
                    }

                    List<SupplierInfo.DataBean.EntryBanks> banks = dataBean.getBanks();//银行分录
                    if (banks == null) {
                        //如果bills为空或者为null或者为空字符串，则执行接下来的代码块
                        msgBuilder.append("第").append(i + 1).append("条数据，银行分录为空不能保存!");
                        SupplierResulText.ResultBean failure = SupplierResulText.failure(i, "银行分录不能为空", banks.toString());
                        results.add(failure);//将返回结果数据存放到集合中
                        supplierResulText.setResult(results);//将集合重新传给返回值参数
                        failCount++;//错误信息+1
                    } else {
                        DynamicObjectCollection banksCollection = supplier.getDynamicObjectCollection("entry_bank");//银行分录
                        DynamicObjectType bankType = banksCollection.getDynamicObjectType();
                        for (int k = 0; k < banks.size(); k++) {
                            SupplierInfo.DataBean.EntryBanks entryBanks = banks.get(k);
                            DynamicObject banksEntry = new DynamicObject(bankType);
                            //同一个银行账号 不能同时存在在不同编码的客商内
                            String bankn = entryBanks.getBANKN();
                            if (bankn != null) {
                                // 检查银行账号是否已存在于其他编码中
                                boolean isBankAccountExists = checkBankAccountExists(bankn);
                                if (!isBankAccountExists) {
                                    banksEntry.set("bankaccount", bankn);//银行账号
                                } else {
                                    msgBuilder.append("第").append(i + 1).append("条数据，银行账号重复，不能保存!");
                                    SupplierResulText.ResultBean failure = SupplierResulText.failure(i, "银行账号已存在于其他编码中", id);
                                    results.add(failure);//将返回结果数据存放到集合中
                                    supplierResulText.setResult(results);//将集合重新传给返回值参数
                                    failCount++;//错误信息+1
                                }
                            }
                            String koinh = entryBanks.getKOINH();
                            banksEntry.set("accountname", koinh);//开户账户名(账户名称)
                            String currencyNum = entryBanks.getCURRENCYCODE();//币种代码
                            DynamicObject currencyNumber = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("Number", "=", currencyNum).toArray());
                            banksEntry.set("currency", currencyNumber);//币种代码
                            if (currencyNum == null) {
                                String currencyname = entryBanks.getCURRENCYNAME();//币种名称
                                DynamicObject currencyName = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("name", "=", currencyname).toArray());
                                banksEntry.set("currency", currencyName);//币种名称
                            }
                            String bankl = entryBanks.getBANKL(); //开户银行通过联行号获取
                            DynamicObject bank = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("union_number", "=", bankl).toArray());
                            banksEntry.set("bank", bank);//开户银行
                            if (bankl == null) {
                                String bankName1 = entryBanks.getBANKN();//开户银行名称
                                DynamicObject bankName2 = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("name", "=", bankName1).toArray());
                                banksEntry.set("bank", bankName2);//开户银行名称
                            }
                            String iban = entryBanks.getBANKS();
                            banksEntry.set("iban", iban);//银行国家代码（国际银行账户号码）
                            //第一行银行信息为默认
                            if (k == 0) {
                                banksEntry.set("isdefault_bank", true);//默认
                            } else {
                                banksEntry.set("isdefault_bank", false);
                            }
                            banksCollection.add(banksEntry);
                        }
                        OperationResult operationResult = OperationServiceHelper.executeOperate("save", "bd_supplier", new DynamicObject[]{supplier});
                        System.out.println();
                        for (IOperateInfo errInfo : operationResult.getAllErrorOrValidateInfo()) {
                            message = errInfo.getMessage();
                        }
                    }
                }
                SupplierResulText.ResultBean resultbean = new SupplierResulText.ResultBean();
                resultbean.setErrors(Collections.singletonList(message));
                if (message != null) {
                    resultbean.setNumber(id);
                    results.add(resultbean);
                    failCount++;
                }
            }
        }
        if (failCount < data.size()) {
            successCount = data.size() - failCount;//成功数量
        }
        supplierResulText.setFailCount(failCount);//失败数量
        supplierResulText.setSuccessCount(successCount);//成功数量
        supplierResulText.setResult(results);//返回结果
        return CustomApiResult.success(supplierResulText);
    }

    private boolean checkBankAccountExists(String bankn) {
        DynamicObject bill = BusinessDataServiceHelper.loadSingle("bd_supplier", new QFilter("entry_bank.bankaccount", "=", bankn).toArray());
        if (bill != null) {
            return true; // 银行账号已存在于其他编码中
        }
        return false;// 银行账号不存在于其他编码中
    }
}
